import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login, userLoginInfo } from '@/request/api.ts'
import { User, UserLoginReq, UserLoginResp } from '@/proto/user.ts'
import { getToken, removeToken, setToken } from '@/utils/auth.ts'

export const userStore = defineStore('user', () => {
  const loginUserInfo = ref<User>(new User({ name: '未登录' }))

  async function userLogin(account: string, password: string) {
    const user: UserLoginResp = await login(
      new UserLoginReq({ account: account, password: password }),
    )
    // 保存一下全局token
    setToken(user.token)
    loginUserInfo.value = user.user
  }

  function userLogout() {
    removeToken()
    loginUserInfo.value = new User({ name: '未登录' })
    window.location.href = '/user/login'
    return
  }

  function setLoginUserInfo(user: User) {
    loginUserInfo.value = user
  }

  return { userLogin, setLoginUserInfo, loginUserInfo, userLogout }
})

// 直接在这里判断是不是有token 有就拿一下用户信息
if (getToken()) {
  userLoginInfo(
    new UserLoginReq({
      account: '1',
      password: '1',
    }),
  ).then((res: User) => {
    userStore().setLoginUserInfo(res)
  })
}
